package it.tukano.swingdeco.menubar;

import it.tukano.fun.Function1;
import java.awt.Component;
import java.awt.event.ActionListener;
import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JMenu;
import javax.swing.JMenuItem;

/**
 * JMenu extension
 * @author pgi
 */
public class JMenuExt extends JMenu {

    /* Serial version of this class */
    private static final long serialVersionUID = 0;

    /**
     * Instance initializer
     */
    public JMenuExt() {
    }

    /**
     * Initializes this menu with a label
     * @param label the label of the menu
     */
    public JMenuExt(String label) {
        super(label);
    }

    public JMenuExt addCheckBox(String label, ButtonGroup group) {
        JCheckBoxMenuItem item = new JCheckBoxMenuItem(label);
        add(item);
        if(group != null) {
            group.add(item);
        }
        return this;
    }

    /**
     * Add a check box to this menu
     * @param label the label of the check box
     * @return this
     */
    public JMenuExt addCheckBox(String label) {
        return addCheckBox(label, null);
    }

    public AbstractButton getButton(String label) {
        for (Component component : getMenuComponents()) {
            if(component instanceof AbstractButton) {
                AbstractButton b = (AbstractButton) component;
                if(b.getText().equals(label)) return b;
            }
        }
        return null;
    }

    public JMenuExt addButtons(String... labels) {
        for (int i = 0; i < labels.length; i++) {
            String string = labels[i];
            add(new JMenuItem(string));
        }
        return this;
    }

    public JMenuExt onActionPerformed(ActionListener listener) {
        for (Component component : getMenuComponents()) {
            if(component instanceof AbstractButton) {
                ((AbstractButton) component).addActionListener(listener);
            }
        }
        return this;
    }

    /**
     * Applies a function to the components of this menu ext
     * @param <T> the type of the scanned components
     * @param itemType the class of the components to get
     * @param fun the function to apply
     * @return this
     */
    public <T> JMenuExt foreach(Class<T> itemType, Function1<T, ?> fun) {
        int itemCount = getMenuComponentCount();
        for (int i= 0; i < itemCount; i++) {
            Component component = getMenuComponent(i);
            if(component != null && itemType.isAssignableFrom(component.getClass())) {
                fun.apply(itemType.cast(component));
            }
        }
        return this;
    }
}
